import axios from "axios"
import sha256 from 'crypto-js/sha256';
import CryptoJS from 'crypto-js'
import { useState ,useRef,useEffect} from "react";

function TransLate(){
    const [translation,setTranslation] = useState([])
    const [context,setContext] = useState('')
    const [contList,setContList] = useState(new Map())
    const [msgList,setMsgList] = useState([])
    const counter = useRef(0)

    useEffect(()=>{
        setMsgList(Array.from(contList.values()))
    },
    [contList])
    // 发送翻译请求
    const transHandle=()=>{
        // const query = '您好，欢迎再次使用有道智云文本翻译API接口服务';
            // contList.add(getMapAddLen(),showTxt)
            setContList(pre=>{
               const preMap = new Map(pre)
               const showTxt = {isSource:true,txt:context}
               counter.current++
               preMap.set(counter.current,showTxt)
            //    console.log('preMap1',counter.current);
               return preMap
            })

        const obj = getYoudaoParams(context)
        axios.get('/api',{params:obj}).then(res=>{
            // console.log('res',res);
            const {data} = res
            // console.log('translation',data.translation);
            setTranslation(data.translation)

           const showTxt = {isSource:false,txt:data.translation[0]}
            // setContList(per=>[...per,showTxt])
             setContList(pre=>{
               const preMap =  new Map(pre)
                counter.current++
               preMap.set(counter.current,showTxt)
                 return preMap
            })
        }).catch(err=>{console.log('err',errr);})
    }

    const getMapAddLen = ()=>{
        return contList.size +1;
    }

    console.log('contList',contList);

    const getYoudaoParams = (query)=>{
        const appKey = '68c484ead4c5d71d';
        const key = 'F1T5UgJs3frEQnDXHItReCOcFwByHTT1';//注意：暴露appSecret，有被盗用造成损失的风险
        const salt = (new Date).getTime();
        const curtime = Math.round(new Date().getTime()/1000);

        // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
        const from = 'zh-CHS';
        const to = 'en';
        const str1 = appKey + truncate(query) + salt + curtime + key;
        const vocabId =  '您的用户词表ID';
        //console.log('---',str1);

        const sign = sha256(str1).toString(CryptoJS.enc.Hex);

       return {
            q: query,
            appKey: appKey,
            salt: salt,
            from: from,
            to: to,
            sign: sign,
            signType: "v3",
            curtime: curtime,
            // vocabId: vocabId,
        }
    function truncate(q){
            const len = q.length;
            if(len<=20) return q;
            return q.substring(0, 10) + len + q.substring(len-10, len);
    }

    }
// $.ajax({
//     url: 'https://openapi.youdao.com/api',
//     type: 'post',
//     dataType: 'jsonp',
//     data: {
//         q: query,
//         appKey: appKey,
//         salt: salt,
//         from: from,
//         to: to,
//         sign: sign,
//         signType: "v3",
//         curtime: curtime,
//         vocabId: vocabId,
//     },
//     success: function (data) {
//         console.log(data);
//     } 
// });


    return (
        <>
        <input type="text" onChange={(e)=>{
            const txt = e.target.value;
            setContext(txt)
       
        }}></input>
        <button onClick={transHandle}>发送</button>
        <div >{msgList.map((item,index)=>(
        <p key={index} className={item.isSource? "right":"left" }>{item.txt}</p>
        ))}</div>
    
        </>
    )
}

export default TransLate